#include "SypEngine.h"

#ifdef CHECKMEM
#include "mmgr.h"
#endif
namespace Syp
{

void MeshInstance::useMesh(BaseMesh* m)
{
	assert(m && "0 passed into MeshInstance::useMesh(), Use MeshInstance::clearMesh() instead");
	//Set current mesh to 0, inform previous owner that we are not using it
	clearMesh();
	if(m)
	{
		//We are now using mesh m
		mesh = m;		
		//Tell the mesh we are using it (For GC purposes) 
		m->addInstance();	
		///Use reccommendation
		useMaterial(m->material);
	}		
}

MeshInstance* MeshInstance::createMeshInstance()
{
	return (new MeshInstance());
}

void MeshInstance::destroyMeshInstance(MeshInstance* mi)
{
	delete mi;
}

void MeshInstance::setVisibility(bool visibility)
{
	visible = visibility;
}

MeshInstance::MeshInstance() : visible(true),mesh(0),speed(1.0f),AnimTime(0.0f), lastTransformedOn(0),animate(true), mode(PERSPECTIVE),material(0),currAnimSet(-1)
{

}

void MeshInstance::useMaterial(const String& filename)
{
	if(filename=="")
	{
		return;
	}
	useMaterial(Material::loadFromFile(filename));	
	
}

Material* MeshInstance::getMaterial()
{
	return material;
}

void MeshInstance::useMaterial(Material* m)
{	
		clearMaterial();
	if(m)
	{
		material = m;
	
		//Increment ref count
		m->addInstance();
	}
	SceneManager::getSceneManager().addInstance(this);
}

void MeshInstance::clearMaterial()
{
	if(material)
	{
		material->removeInstance();
	}
	material = 0;
	//Has to be done to remove Renderables with a Pass attached.
	SceneManager::getSceneManager().removeInstance(this);
}


void MeshInstance::clearMesh()
{
	//Remove from Renderque, we have to do this so that the Renderer does not go about drawing an Instance which has no mesh.
	SceneManager::getSceneManager().removeInstance(this);
	//If there is a previous owner, inform the mesh that we no longer are using it
	if(mesh)
	{
		//Decrease reference count
		mesh->removeInstance();		
	}
	mesh = 0;
}

void MeshInstance::clearAll()
{
	clearMesh();
	clearMaterial();
//	clearTexture();
}

MeshInstance::~MeshInstance()
{
	//Remove from Render que, just incase user forgot to remove MeshInstance
	SceneManager::getSceneManager().removeInstance(this);
	//Release all resources so that they are no longer bound.
	clearAll();
}

}
